from openai import OpenAI
import json
import time
from bot_api import update_message

with open("./ignore/config.json", "r") as f:
    config = json.load(f)

def ai_talk(content, msg_id):

    client = OpenAI(api_key=config["ai_key"], base_url="https://api.deepseek.com")
    start_time = time.time()
    # 使能流式输出
    response = client.chat.completions.create(
        model="deepseek-chat",
        messages=[
            {"role": "system", "content": "You are a helpful assistant"},
            {"role": "user", "content": content},
        ],
        stream=True  # 设置流式输出为 True
    )

    # create variables to collect the stream of chunks
    collected_chunks = []
    collected_messages = []

    # iterate through the stream of events
    for chunk in response:
        # print(chunk)
        chunk_time = time.time() - start_time  # calculate the time delay of the chunk
        collected_chunks.append(chunk)  # save the event response
        chunk_message = chunk.choices[0].delta.content  # extract the message
        collected_messages.append(chunk_message)  # save the message
        print(f"Message received {chunk_time:.2f} seconds after request: {chunk_message}")  # print the delay and text
        update_message(" ".join(collected_messages), msg_id)

    # # print the time delay and text received
    # print(f"Full response received {chunk_time:.2f} seconds after request")
    # full_reply_content = ''.join(collected_messages)
    # print(f"Full conversation received: {full_reply_content}")


if __name__ == "__main__":
    ai_talk("Hello")